/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.jjsoft.disco.gco.view;

import com.jjsoft.disco.gco.mdl.Configuracion;
import com.jjsoft.disco.gco.mdl.Diario;
import com.jjsoft.disco.gco.mdl.Usuario;
import com.jjsoft.disco.gco.ngc.ConfiguracionManager;
import com.jjsoft.disco.gco.ngc.DiarioManager;
import com.jjsoft.disco.gco.ngc.UsuarioManager;
import com.jjsoft.disco.gco.util.configuraciones;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.UIManager;

/**
 *
 * @author johnny
 */
public class VLoggin extends javax.swing.JFrame {

    /**
     * Creates new form VLoggin
     */
    int intentos = 0;
    UsuarioManager um = new UsuarioManager();
    Usuario usuario;

    public VLoggin() {
        //this.setIconImage(new javax.swing.ImageIcon(getClass().getResource("/img/1362798841_CellPhone.png")).getImage());
        initComponents();
        intentos = 0;
        String dirIp = "";
        try {
            dirIp = InetAddress.getLocalHost().getHostAddress();
        } catch (UnknownHostException ex) {
            Logger.getLogger(VConfiguracionSis.class.getName()).log(Level.SEVERE, null, ex);
        }
        ConfiguracionManager cm = new ConfiguracionManager();
        Configuracion configuracion;
        configuracion = cm.verConfiguracion(dirIp);
        if (configuracion != null) {
            configuraciones.Direccion = configuracion.getDireccion();
            configuraciones.NombreLocal = configuracion.getNombreLocal();
            configuraciones.NombrePropietario = configuracion.getNombreDuenio();
            configuraciones.Telefono = configuracion.getTelefono();
            configuraciones.impresoraFacturas = configuracion.getImpresora();
            configuraciones.dirIP = configuracion.getDirIP();
            configuraciones.ruc = configuracion.getRuc();
            configuraciones.barras = configuracion.getBarras();
            configuraciones.logo = configuracion.getLogo();
            configuraciones.iva = configuracion.getIva();
            configuraciones.coverm=configuracion.getCoverm();
            configuraciones.consumiblem=configuracion.getConsumiblem();
            configuraciones.coverh=configuracion.getCoverh();
            configuraciones.consumibleh=configuracion.getConsumibleh();
        }

    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel2 = new javax.swing.JLabel();
        cmdIngresar = new javax.swing.JButton();
        cmdCancelar = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        jSeparator1 = new javax.swing.JSeparator();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        txtPassword = new javax.swing.JPasswordField();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("INGRESO");
        setBackground(new java.awt.Color(255, 0, 51));

        jLabel2.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel2.setForeground(new java.awt.Color(102, 102, 102));
        jLabel2.setText("Tarjeta:");

        cmdIngresar.setBackground(new java.awt.Color(204, 204, 255));
        cmdIngresar.setFont(new java.awt.Font("Tahoma", 1, 13)); // NOI18N
        cmdIngresar.setForeground(new java.awt.Color(11, 2, 192));
        cmdIngresar.setText("INGRESAR");
        cmdIngresar.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        cmdIngresar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmdIngresarActionPerformed(evt);
            }
        });

        cmdCancelar.setBackground(new java.awt.Color(204, 204, 255));
        cmdCancelar.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        cmdCancelar.setForeground(new java.awt.Color(11, 2, 192));
        cmdCancelar.setText("SALIR");
        cmdCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmdCancelarActionPerformed(evt);
            }
        });

        jLabel3.setFont(new java.awt.Font("Ubuntu", 0, 18)); // NOI18N
        jLabel3.setForeground(new java.awt.Color(11, 2, 192));
        jLabel3.setText("ACCESO AL SISTEMA");

        jLabel4.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        jLabel4.setForeground(new java.awt.Color(102, 102, 102));
        jLabel4.setText("Por favor ingrese su usuario y contraseña para continuar");

        jLabel5.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/candado.png"))); // NOI18N

        txtPassword.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.LOWERED));
        txtPassword.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtPasswordKeyPressed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(127, 127, 127)
                        .addComponent(jLabel3))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(28, 28, 28)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 406, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel4)
                                    .addGroup(layout.createSequentialGroup()
                                        .addGap(37, 37, 37)
                                        .addComponent(jLabel2)
                                        .addGap(18, 18, 18)
                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                            .addComponent(txtPassword, javax.swing.GroupLayout.PREFERRED_SIZE, 177, javax.swing.GroupLayout.PREFERRED_SIZE)
                                            .addGroup(layout.createSequentialGroup()
                                                .addComponent(cmdIngresar, javax.swing.GroupLayout.PREFERRED_SIZE, 97, javax.swing.GroupLayout.PREFERRED_SIZE)
                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                                .addComponent(cmdCancelar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 113, javax.swing.GroupLayout.PREFERRED_SIZE)))))
                .addContainerGap(30, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(14, 14, 14)
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel4)
                        .addGap(33, 33, 33)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(txtPassword, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel2))
                        .addGap(51, 51, 51)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(cmdIngresar, javax.swing.GroupLayout.DEFAULT_SIZE, 32, Short.MAX_VALUE)
                            .addComponent(cmdCancelar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                    .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 142, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(27, Short.MAX_VALUE))
        );

        setSize(new java.awt.Dimension(499, 297));
        setLocationRelativeTo(null);
    }// </editor-fold>//GEN-END:initComponents

    private void cmdIngresarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdIngresarActionPerformed
        // TODO add your handling code here:
        usuario = um.buscarPorPassword(txtPassword.getText());
        if (usuario != null) {
            configuraciones.usuario = usuario;
            if (usuario.getRol() == 1) {
                DiarioManager dm = new DiarioManager();
                Diario diario = dm.buscaDiario(usuario);
                if (diario == null) {
                    String caja = JOptionPane.showInputDialog("Ingrese la caja inicial");
                    double cajaInicial = 0;
                    if (caja == null) {
                        return;
                    } else {
                        try {
                            cajaInicial = Double.parseDouble(caja);
                        } catch (Exception ex) {
                            JOptionPane.showMessageDialog(rootPane, "Asegurese de ingresar un valor numerico");
                            return;
                        }
                    }
                    diario = new Diario();
                    diario.setEstado(0);
                    diario.setFecha(new Date());
                    diario.setIdUsuario(usuario);
                    diario.setValor(cajaInicial);
                    dm.crearDiario(diario);

                }
                configuraciones.diario = diario;
                new VPrincipalCajero().show();

            } else if (usuario.getRol() == 2) {
                String barra=JOptionPane.showInputDialog("Ingrese el número de la barra");
                    int numBarra=0;
                    if(barra==null)
                    {
                        return;
                    }
                    else
                    {
                        try{
                            numBarra=Integer.parseInt(barra);
                            if(numBarra==0 || numBarra>configuraciones.barras)
                            {
                                JOptionPane.showMessageDialog(rootPane, "Barra Incorrecta");
                                return;
                            }
                            configuraciones.barra=numBarra;
                            
                        }
                        catch(Exception ex)
                        {
                            JOptionPane.showMessageDialog(rootPane, "Asegurese de ingresar un valor numerico");
                            return;
                        }
                    }
                new VPrincipalAdmin(0).show();
            }
            else
            {
                new VPrincipalAdmin(0).show();
            }
            this.dispose();
        } else {
            JOptionPane.showMessageDialog(rootPane, "No exite un usuario con esa tarjeta");
            txtPassword.setText("");
            txtPassword.requestFocus();
            intentos++;
            if (intentos == 3) {
                JOptionPane.showMessageDialog(rootPane, "Ah alcanzado el numero permitido de intentos");
                System.exit(0);
            }
        }
    }//GEN-LAST:event_cmdIngresarActionPerformed

    private void cmdCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdCancelarActionPerformed
        // TODO add your handling code here:
        System.exit(0);
    }//GEN-LAST:event_cmdCancelarActionPerformed

    private void txtPasswordKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtPasswordKeyPressed
        // TODO add your handling code here:
        if (evt.getKeyCode() == 10) {
            cmdIngresar.doClick();
        }
    }//GEN-LAST:event_txtPasswordKeyPressed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(VLoggin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(VLoggin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(VLoggin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(VLoggin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
        //JFrame.setDefaultLookAndFeelDecorated(true);

        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Exception e) {
            System.out.println("Error setting native LAF: " + e);
        }
        //SubstanceLookAndFeel.setSkin("org.pushingpixels.substance.api.skin.ModerateSkin");

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                //org.pushingpixels.substance.api.skin.BusinessBlackSteelSkin;
                //SubstanceLookAndFeel.setSkin("org.pushingpixels.substance.api.skin.BusinessBlackSteelSkin");
                new VLoggin().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton cmdCancelar;
    private javax.swing.JButton cmdIngresar;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JPasswordField txtPassword;
    // End of variables declaration//GEN-END:variables
}
